package com.crois.barrier.transport.transport.init;


import com.crois.barrier.common.factory.BarrierThreadFactory;
import com.crois.barrier.transport.heartbeat.HeartbeatSenderProvider;
import com.crois.barrier.transport.transport.HeartBeatSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@InitOrder(-1)
public class HeartbeatSenderInitFunc implements InitFunc{


    private static final Logger LOGGER = LoggerFactory.getLogger(HeartbeatSenderInitFunc.class);

    private ScheduledExecutorService pool = null;

    private void initSchedulerIfNeed() {
        if (pool==null){
            pool = new ScheduledThreadPoolExecutor(2
                    ,new BarrierThreadFactory(true,"barrier-heartbeat-send-task")
                    ,new ThreadPoolExecutor.DiscardOldestPolicy());
        }
    }


    @Override
    public void init(String serverName,String adminServer, String localAddress, int serverPort) throws Exception {
        //获取 HeartBeatSender
        HeartBeatSender sender = HeartbeatSenderProvider.getHeartbeatSender();
        if (sender==null){
            LOGGER.warn("[HeartbeatSenderInitFunc] WARN: No HeartbeatSender loaded");
            return;
        }
        initSchedulerIfNeed();
        long interval = retrieveInterval(sender);
        scheduleHeartbeatTask(serverName,sender, interval,adminServer,localAddress,serverPort);

    }

    private void scheduleHeartbeatTask(String serverName,HeartBeatSender sender, long interval, String adminServer, String localAddress, int serverPort) {
        pool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    sender.sendHeartbeat(serverName,adminServer,localAddress,serverPort);
                } catch (Throwable e) {
                    LOGGER.warn("[HeartbeatSender] Send heartbeat error", e);
                }
            }
        },5000,interval, TimeUnit.MILLISECONDS);

        LOGGER.info("[HeartbeatSenderInit] HeartbeatSender started: "
                + sender.getClass().getCanonicalName());
    }



    long retrieveInterval(HeartBeatSender sender) {
        long sendInterval = sender.intervalMs();
        LOGGER.info("[HeartbeatSenderInit] Heartbeat interval not configured in "
                + "config property or invalid, using sender default: " + sendInterval);
        return sendInterval;
    }
}
